﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using EQT.Model;
using EQT.Dal;
using System.Collections.Generic;
using System.IO;
using Brettle.Web.NeatUpload;


public partial class DirFilesPage : System.Web.UI.Page
{
    private DaDirFile dadf = new DaDirFile(DaCommon.DefaultDb);
    private DaTfile datfile = new DaTfile(DaCommon.DefaultDb);

    protected void Page_Load(object sender, EventArgs e)
    {
    
        
        if (!Page.IsPostBack)
        {
            BindDirTree();
            if (dirTreeView.Nodes.Count > 0)
            {                
                dirTreeView.Nodes[0].Select();
                BindFilesDgv(dirTreeView.Nodes[0].Value);
                lbCurrentDir.Text = dirTreeView.SelectedNode.Text;
            }
            AspNetPager1.PageSize = 20;
            //SetPanelView(PanelShowMask.defaultPanelShowMask);

        }
       
         
    }

    /// <summary>
    /// 显示的页码发生改变
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        BindFilesDgv(dirTreeView.SelectedNode.Value);
    }

    /// <summary>
    /// 绑定目录树
    /// </summary>
    private void BindDirTree()
    {
        dirTreeView.Nodes.Clear();
        List<MoDirFile> listRoot= dadf.GetEntities(" WHERE  DF_FLAG='R'");
        if (Utility.GlobalLog.IsDebugEnabled) Utility.GlobalLog.Debug(String.Format("发现{0}个根", listRoot.Count));
        Dictionary<string, TreeNode> tnDic = new Dictionary<string, TreeNode>();

        for (int i = 0; i < listRoot.Count; i++)
        {
            DataSet ds= dadf.GetDirTreeDs(listRoot[0].Df_Id);//找到孩子
            if (ds != null && ds.Tables.Count == 1)
            {
                #region 抽出节点树
                DataTable dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    TreeNode tnRoot = new TreeNode((string)dt.Rows[0]["DF_NAME"], (string)dt.Rows[0]["DF_ID"]);
                    tnDic.Add((string)dt.Rows[0]["DF_ID"], tnRoot);
                    for (int j = 1; j < dt.Rows.Count; j++)//循环添加孩子
                    {
                        string parent_id = (string)dt.Rows[j]["PARENT_DID"];
                        if (tnDic.ContainsKey(parent_id)) //如果父节点已经在集合中
                        {
                            TreeNode tn = new TreeNode((string)dt.Rows[j]["DF_NAME"],
                                (string)dt.Rows[j]["DF_ID"]);

                            tnDic[parent_id].ChildNodes.Add(tn);
                            tnDic.Add(tn.Value, tn);                             

                        }
                        else //新的父节点，这肯定是不可能的
                        {
                            throw new EqtException("在目录树中，发现了非根目录节点.根不能处于其他节点之下，数据库完整性遭到破坏！");

                        }

                    }
                    //Note:只向树添加顶级根节点                    
                    dirTreeView.Nodes.Add(tnRoot);
                }
                else
                {
                    if (Utility.GlobalLog.IsWarnEnabled) Utility.GlobalLog.Warn("没有目录数据!");
                }
                #endregion
            }//添加过程执行完毕
            else
            {
                throw new EqtException("查询目录失败，不可返回空数据集");
            }
            tnDic.Clear();//清空字典，以备再一次循环
            dirTreeView.ExpandAll();
            dirTreeView.ExpandDepth = 3;
        }
    
      
    }




    /// <summary>
    /// 绑定某目录下的所有文件列表
    /// </summary>
    /// <param name="dir_id"></param>
    private void BindFilesDgv(string dir_id)
    {
        AspNetPager1.CurrentPageIndex = 0;
        int count = 0;
        GridView1.DataSource = DaCommon.GetPaginationData(DaTfile.SQL_SELECT+String.Format(" INNER JOIN DIR_FILE ON DF_ID=FILE_ID WHERE  DIR_FILE.PARENT_DID='{0}'" ,dir_id),
        SiteConfig.PageSize, AspNetPager1.CurrentPageIndex - 1, " File_ID ", out count);
        GridView1.DataBind();
        AspNetPager1.PageSize = SiteConfig.PageSize;
        AspNetPager1.RecordCount = count;
        if (count == 0)
        {
            labMsg.Visible = true;
            labMsg.Text = "该目录下无文件";
        }
        else
        {
            labMsg.Text = String.Empty;
            labMsg.Visible = false;
        }

        btnAddFile.Attributes.Add("OnClick", string.Format("InvokePopUploadDocs('{0}','{1}')",
                dirTreeView.SelectedNode.Value, Server.HtmlEncode(dirTreeView.SelectedNode.Text)));
    }


    protected void btnAddDir_Click(object sender, EventArgs e)
    {
       // SetPanelView(PanelShowMask.addPanelShowMask);
        this.ModalPopupExtenderAddDir.Show();
      
    }
    
   
    protected void dirTreeView_SelectedNodeChanged(object sender, EventArgs e)
    {
        if (dirTreeView.SelectedNode != null)
        {
            
            BindFilesDgv(dirTreeView.SelectedNode.Value);
            lbCurrentDir.Text = dirTreeView.SelectedNode.Text;
                      
            
        }
        else
        {
            labMsg.Visible = true;
            labMsg.Text = "您未选择任何目录！";
        }
    }


      
    protected void btnRemoveDir_Click(object sender, EventArgs e)
    {
       // SetPanelView(PanelShowMask.delPanelShowMask);
        lbDirToDelInfo.Text = String.Format("您将要删除 {0} 目录！", dirTreeView.SelectedNode.Text);
        this.ModalPopupExtender1.Show();
    }
    /// <summary>
    /// 删除文件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GvDelete_Click(object sender, EventArgs e)
    {
        LinkButton btn = sender as LinkButton;
        GridViewRow gvr = (GridViewRow)btn.NamingContainer;
        string file_id = (string)GridView1.DataKeys[gvr.RowIndex].Value;     
        MoTfile mo = datfile.GetEntity(file_id);
        
        try
        {
            string file_path = Utility.GetLocalFileFromUri(mo.File_Url);
            System.IO.File.Delete(file_path);
            datfile.Delete(file_id);
            dadf.Delete(file_id);
            Utility.GlobalLog.Warn(String.Format("删除了文件{0},{1}", file_id, mo.File_Url));
        }
        catch (Exception ex)
        {
            Utility.GlobalLog.Error("删除文件失败!", ex);
            Utility.SiteError("删除文件失败！", Response); 
        }
        BindFilesDgv(dirTreeView.SelectedNode.Value);
      
    }

    /// <summary>
    /// 下载文件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GvDownload_Click(object sender, EventArgs e)
    {
        LinkButton btn = sender as LinkButton;
        GridViewRow gvr = (GridViewRow)btn.NamingContainer;
        string file_id = (string)GridView1.DataKeys[gvr.RowIndex].Value;
        MoTfile mo = datfile.GetEntity(file_id);
    

       
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton l = (LinkButton)e.Row.FindControl("GvDelete");
            l.Attributes.Add("onclick", "javascript:return " +
            "confirm(' 您确认删除文件 " +
            DataBinder.Eval(e.Row.DataItem, "FILE_NAME") + "')");


            LinkButton lbtn_rename = (LinkButton)e.Row.FindControl("GVLB_Rename");
            string url = String.Format("rename.aspx?fileid={0}&filename={1}&pccid={2}",
               DataBinder.Eval(e.Row.DataItem, "FILE_ID"),
               Server.UrlEncode(  DataBinder.Eval(e.Row.DataItem, "FILE_NAME").ToString()),btnHiddenAddFile.ClientID
            );
            lbtn_rename.Attributes.Add("onclick", String.Format("javascript:window.open('{0}','重命名','height=400,width=400,resizable=no');return true;",
                url));

             

        }

    }

 

    protected void btnDelDir_OK(object sender, EventArgs e)
    {        
        //删除目录
        try
        {
            dadf.Delete(dirTreeView.SelectedValue);
            BindDirTree();
            //SetPanelView(PanelShowMask.defaultPanelShowMask);
            lbDirToDelInfo.Text = String.Empty;
            this.ModalPopupExtender1.Hide();
        }
        catch (DalException de)
        {
            Utility.GlobalLog.Warn("删除目录失败", de);
            lbDirToDelInfo.Text = String.Format("删除目录 {0} 失败！因为该目录不为空！",dirTreeView.SelectedNode.Text);
        }
        
       
    }
    protected void btnAddDirOK_Click(object sender, EventArgs e)
    {
        UserContext uc = Session["USER_CONTEXT"] as UserContext;
        string user_id=null;
        if (uc != null) user_id = uc.UserID;
        MoDirFile modf = new MoDirFile(SequenceKeys.GenerateDirectoryID(), user_id, dirTreeView.SelectedValue, txtSubDir.Text, "D", null, DateTime.Now);
        dadf.Add(modf);
        BindDirTree();
        this.ModalPopupExtenderAddDir.Hide();

       
    }
   
    protected void btnAddFile_Click(object sender, EventArgs e)
    {
      
        dirTreeView_SelectedNodeChanged(dirTreeView, e);
    }

    /// <summary>
    /// 刷新列表
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GVLB_Rename_Click(object sender, EventArgs e)
    {
        dirTreeView_SelectedNodeChanged(dirTreeView, e);
    }
}
